package com.dysm.spring.security.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class MyClientService implements ClientDetailsService, InitializingBean {

    private final List<ClientDetails> clientDetails = new ArrayList<>();

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        return clientDetails.stream().filter(c -> Objects.equals(c.getClientId(), clientId)).findAny().orElse(null);
    }

    @Override
    public void afterPropertiesSet() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        BaseClientDetails client1 = new BaseClientDetails("C20220801000001", "security-resource-id", "write,read",
                "client_credentials,implicit,authorization_code,refresh_ token,password",
                "admin", "https://www.baidu.com");
        client1.setClientSecret(bCryptPasswordEncoder.encode("P20220801000001"));
        BaseClientDetails client2 = new BaseClientDetails("C20220801000002", "security-resource-id", "write,read",
                "client_credentials,implicit,authorization_code,refresh_ token,password",
                "admin", "https://www.baidu.com");
        client2.setClientSecret(bCryptPasswordEncoder.encode("P20220801000002"));
        BaseClientDetails client3 = new BaseClientDetails("C20220801000003", "security-resource-id", "write,read",
                "client_credentials,implicit,authorization_code,refresh_ token,password",
                "admin", "https://www.baidu.com");
        client3.setClientSecret(bCryptPasswordEncoder.encode("P20220801000003"));
        clientDetails.add(client1);
        clientDetails.add(client2);
        clientDetails.add(client3);
    }
}
